package com.ghc.service.impl;

import com.ghc.entity.AuthCode;
import com.ghc.repository.AuthCodeRepository;
import com.ghc.service.CreateCodeService;
import com.ghc.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class CreateCodeServiceImpl implements CreateCodeService {

    @Reference(timeout = 3000)
    private EmailService emailService;

    private final AuthCodeRepository authCodeRepository;

    @Override
    public Boolean create(String email) {
        String code = RandomUtils.nextInt(899999)+100000+"";
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(LocalDateTime.now());
        authCode.setExpiretime(LocalDateTime.now().plusMinutes(5));
        AuthCode save = authCodeRepository.save(authCode);
        log.info("当前时间： {}", LocalDateTime.now());
        if (emailService.send(email, code)){
            return true;
        }
        log.info("当前时间： {}", LocalDateTime.now());
        Integer id = save.getId();
        authCodeRepository.deleteById(id);
        return false;
    }
}
